<template>
  <div id="art-detail">
    <div class="main-box" v-if="detail.shop_hash != null">
      <div class="art-info-box">
        <!-- 左侧预览 -->
        <div class="cover-box">
          <div class="cover" v-if="detail.classify == '图片'">
            <el-image
              :src="ipfsHash + detail.shop_hash"
              :previewSrcList="[ipfsHash + detail.shop_hash]"
            ></el-image>
            <!-- 下载按钮 -->
            <div class="download-btn" @click="downloadArt(detail.shop_hash)" v-if="detail.owner == $store.getters.user_address">
              下载
            </div>
          </div>
          <div class="video" v-if="detail.classify == '视频'">
            <video :src="detail.shop_hash | ipfsHash" controls></video>
          </div>
        </div>
        <!-- 右侧面板 -->
        <div class="panel">
          <div class="info">
            <!-- 艺术品名称 -->
            <div class="art-name">
              {{ detail.title }}
            </div>
            <!-- 上架信息 -->
            <div class="tip count-info">
              <!-- 售价 {{ detail.price }} ETH <i class="icon-ETH iconfont"></i> -->
              <div>
                <span
                  ><i class="icon-eye-fill iconfont"></i
                  ><span style="margin-left: 5px"
                    >热度 {{ detail.hot }}</span
                  ></span
                >
              </div>
              <div>
                <span
                  class="like-btn"
                  :class="{ liked: detail.iscolletion == 1 }"
                  @click="handelLike"
                >
                  <i class="icon-Love iconfont"></i>
                  <span class="like-count">{{ detail.collection_num }}</span>
                </span>
              </div>
            </div>
            <div class="create-time">
              <span class="tip">最近上架时间: {{ detail.put_time }}</span>
            </div>

            <!-- 创作者和持有者信息 -->
            <div class="creatorInfo-owner-box">
              <div>
                <div class="tip">创作者</div>
                <div
                  class="user-box"
                  @click="$router.push(`/user/${detail.creator_address}`)"
                >
                  <div class="avatar">
                    <img
                      :src="detail.creator_logo | ipfsHash"
                      alt=""
                      v-if="detail.creator_logo != null"
                    />
                    <RandomAvatar
                      :user_address="detail.creator_address"
                      v-if="detail.creator_logo == null"
                    />
                  </div>
                  <div class="nickname" v-if="detail.creator_name != null">
                    @{{ detail.creator_name }}
                  </div>
                  <div class="nickname" v-if="detail.creator_name == null">
                    {{ detail.creator_address | filterAddress }}
                  </div>
                </div>
              </div>
              <div>
                <div class="tip">目前持有者</div>
                <div
                  class="user-box"
                  @click="$router.push(`/user/${detail.owner}`)"
                >
                  <div class="avatar">
                    <img
                      :src="detail.owner_logo | ipfsHash"
                      alt=""
                      v-if="detail.owner_logo != null"
                    />
                    <RandomAvatar
                      :user_address="detail.owner"
                      v-if="detail.owner_logo == null"
                    />
                  </div>
                  <div class="nickname" v-if="detail.owner_name != null">
                    @{{ detail.owner_name }}
                  </div>
                  <div class="nickname" v-if="detail.owner_name == null">
                    {{ detail.owner | filterAddress }}
                  </div>
                </div>
              </div>
            </div>
            <!-- 合集信息 -->
            <div class="tip" v-if="detail.array_id != null">合集</div>
            <div class="collection-box" v-if="detail.array_id != null">
              <div
                class="collection"
                @click="$router.push('/collection/' + detail.array_id)"
              >
                <div class="col-cover">
                  <img :src="detail.array_logo | ipfsHash" alt="" />
                </div>
                <div class="col-name">{{ detail.array_name }}</div>
              </div>
            </div>
            <!-- 类型 -->
            <div class="tip">类型：{{ detail.classify }}</div>
            <!-- 描述信息 -->
            <div class="tip">描述信息：</div>
            <!-- <div class="desc">
              一旦利用区块链铸造NFT，这一NFT便会成为独一无二的代币，任何人都可以查阅，以确定元数据、拥有权历史、TokenID、区块链地址和其他相关资料。此外，由于区块链交易可供公众查阅，买家可以看到初次铸造NFT的地址。
            </div> -->
            <div class="desc">
              {{ detail.info == null ? "无描述信息" : detail.info }}
            </div>
            <!-- 拍卖时间信息 -->
            <div
              class="bid-time-box"
              v-if="
                detail.form_of_sale == '拍卖' &&
                leftTime > 0 &&
                startTime < new Date().getTime()
              "
            >
              <div class="bid-tip">距离结束</div>
              <div class="bid-time">
                {{
                  parseInt(new Date(leftTime).getTime() / 1000 / 60 / 60)
                }}小时{{ leftTime | formatDate("mm分ss秒") }}
              </div>
            </div>
            <div
              class="bid-time-box gray"
              v-if="detail.form_of_sale == '拍卖' && leftTime < 0"
            >
              <div class="bid-tip">拍卖已结束</div>
            </div>
            <div
              class="bid-time-box warring"
              v-if="
                detail.form_of_sale == '拍卖' &&
                startTime > new Date().getTime()
              "
            >
              <div class="bid-tip">拍卖未开始</div>
              <div class="bid-time">
                开始时间 {{ startTime | formatDate("yyyy-MM-dd hh:mm:ss") }}
              </div>
            </div>
            <!-- 竞拍历史 -->
            <div v-if="detail.form_of_sale == '拍卖'">
              <div class="history-header">
                <div
                  class="history-tip"
                  :class="{ active: isShowBid }"
                  @click="isShowBid = true"
                >
                  竞价记录
                </div>
                <div
                  class="history-tip"
                  :class="{ active: !isShowBid }"
                  @click="isShowBid = false"
                >
                  交易历史
                </div>
              </div>
              <!-- 竞价 -->
              <div class="bid-history-box" v-if="isShowBid">
                <History
                  :data="{
                    user_address: bid.bidder,
                    time: bid.bidTime,
                    totalPrice: bid.value,
                    info: '出价',
                  }"
                  v-for="bid in bids"
                  :key="bid.bidTime"
                />
              </div>
              <!-- 历史 -->
              <div class="transaction-history-box" v-if="!isShowBid">
                <History
                  :data="{
                    user_address: tran.to,
                    time: tran.tranTime,
                    totalPrice: tran.price,
                    info: index == 0 ? '铸造' : '出价',
                  }"
                  v-for="(tran, index) in trans"
                  :key="tran.tranTime"
                />
              </div>
            </div>
            <!-- 交易历史 -->
            <div v-if="detail.form_of_sale == '定价出售'">
              <div class="history-header">
                <div class="history-tip active">交易历史</div>
              </div>
              <div class="transaction-history-box">
                <History
                  :data="{
                    user_address: tran.to,
                    time: tran.tranTime,
                    totalPrice: tran.price,
                    info: index == trans.length - 1 ? '铸造' : '出价',
                  }"
                  v-for="(tran, index) in trans"
                  :key="tran.tranTime"
                />
              </div>
            </div>
          </div>
          <!-- 底部操作栏 -->
          <div
            class="btn-box"
            v-if="
              detail.form_of_sale == '定价出售' && detail.status == 'selling'
            "
          >
            <div class="price">
              价格：{{ detail.price | weiToEth }} ETH
              <i class="icon-ETH iconfont"></i>
            </div>
            <div
              class="buy-btn-gray"
              v-if="$store.getters.user_address == detail.owner"
            >
              立即购买
            </div>
            <div
              class="buy-btn"
              v-if="$store.getters.user_address != detail.owner"
              @click="$store.dispatch('showComfirmBuy', true)"
            >
              立即购买
            </div>
          </div>

          <!-- 底部操作栏 拍卖 -->
          <div
            class="btn-box"
            v-if="detail.form_of_sale == '拍卖' && detail.status == 'selling'"
          >
            <div class="price" v-if="curAuction.length != 0">
              当前最高价：{{ curAuction["highestBid"] | weiToEth }} ETH
              <i class="icon-ETH iconfont"></i>
            </div>
            <div
              class="buy-btn"
              @click="$store.dispatch('showComfirmBuy', true)"
              v-if="
                $store.getters.user_address != detail.owner &&
                leftTime > 0 &&
                startTime < new Date().getTime()
              "
            >
              出价
            </div>
            <template v-if="bids.length != 0">
              <div
                class="buy-btn"
                @click="comfirmBid"
                v-if="
                  leftTime < 0 &&
                  bids[0].bidder == $store.getters.user_address &&
                  detail.status == 'selling'
                "
              >
                确认交易
              </div>
            </template>
            <template v-if="bids.length == 0">
              <div
                class="buy-btn"
                @click="comfirmBid"
                v-if="
                  leftTime < 0 &&
                  detail.owner == $store.getters.user_address &&
                  detail.status == 'selling'
                "
              >
                确认交易
              </div>
            </template>
            <template v-if="bids.length != 0">
              <div
                class="buy-btn-gray"
                v-if="
                  $store.getters.user_address ==
                    (detail.owner ||
                      leftTime < 0 ||
                      startTime > new Date().getTime()) &&
                  bids[0].bidder != $store.getters.user_address
                "
              >
                出价
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <!-- 蒙版 -->
    <!-- <div
      class="detail-mask"
      :style="{ background: 'url(' + detail.shop_hash + ')' }"
    ></div> -->
    <!-- 确认购买组件 -->
    <ComfirmBuy />
  </div>
</template>

<script>
import { mapState } from "vuex";
import History from "./History";
import ComfirmBuy from "@/components/ComfirmBuy";
import { collete } from "@/api";
import getAbi from "@/utils/contractAbi";
export default {
  name: "detail",
  components: { History, ComfirmBuy },
  data() {
    return {
      time: new Date(),
      // 定时器
      timer: {},
      // 剩余时间
      leftTime: "",
      // 是否展示竞价记录
      isShowBid: true,

      // ipfs
      ipfsHash: "http://172.17.147.23:8888/ipfs/",

      detail: {},

      id: null,

      // 当前拍卖会信息
      curAuction: [],

      // bids 合约返回的竞价记录
      bids: [],

      // 合约返回的所有交易记录
      trans: [],
    };
  },
  mounted() {
    let { id } = this.$route.params;
    this.id = id;
    this.$store.dispatch("artDetail", id);
    // 开启定时器
  },
  computed: {
    ...mapState({
      artDetail: (store) => store.artDetail.artDetail,
    }),

    startTime() {
      if (this.curAuction.length == 0) {
        return "";
      } else {
        return this.curAuction.auctionStartTime * 1000;
      }
    },

    endTime() {
      if (this.curAuction.length == 0) {
        return "";
      } else {
        return this.curAuction.auctionEndTime * 1000;
      }
    },
  },
  watch: {
    async artDetail(newValue) {
      this.detail = newValue;

      let abi = await getAbi();
      if (newValue.form_of_sale == "拍卖") {
        // 获取拍卖场
        abi.methods
          .getCurAunction(newValue.nft_id)
          .call()
          .then((res) => (this.curAuction = res));

        // 获取竞拍历史
        abi.methods
          .returnBids(newValue.nft_id)
          .call()
          .then((res) => {
            let result = [];
            if (res.length != 0) {
              for (var i = res.length - 1; i >= 0; i--) {
                result.push(res[i]);
              }
            }

            // console.log(result);
            this.bids = result;
          });
      }

      // 获取所有的交易记录
      try {
        abi.methods
          .showTranInfo(newValue.nft_id)
          .call()
          .then((res) => {
            let result = [];
            for (var i = res.length - 1; i >= 0; i--) {
              result.push(res[i]);
            }
            // console.log(result);
            this.trans = result;
          })
          .catch(console.log);
      } catch (err) {}
    },

    endTime(newValue) {
      this.timer = setInterval(() => {
        this.leftTime = newValue - new Date().getTime();
      }, 1000);
    },
  },
  methods: {
    // 收藏和取消收藏
    async handelLike() {
      let result = await collete({
        user_address: this.$store.getters.user_address,
        shop_id: this.detail.id,
        type: "shop",
      });
      if (result.flag) {
        this.$message.success(result.msg);
        // 取消收藏
        if (this.detail.iscolletion == 1) {
          this.detail.iscolletion = 0;
          this.detail.collection_num -= 1;
        } else {
          this.detail.iscolletion = 1;
          this.detail.collection_num += 1;
        }
        // 重新获取数据
        // this.$store.dispatch("artDetail", this.id);
      } else {
        this.$message.error(result.msg);
      }
    },

    // 确认交易
    comfirmBid() {
      // 提示
      let msg;
      if (this.detail.owner == this.$store.getters.user_address) {
        msg = "拍卖结束，无人参与竞拍，请确认";
      } else if (this.bids[0].bidder == this.$store.getters.user_address) {
        msg = "竞拍成功，请确认";
      }
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let abi = await getAbi();
        let user_address = this.$store.getters.user_address;
        abi.methods
          .tranferWorks(this.detail.nft_id)
          .send({ from: user_address })
          .then((res) => {
            console.log(res);
            this.$message.success("交易成功");
            this.$router.go(-1);
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("交易错误，请检查钱包状态");
          });
      });
    },

    getImageBase64(image) {
      const canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, image.width, image.height);
      // 获取图片后缀名
      const extension = image.src
        .substring(image.src.lastIndexOf(".") + 1)
        .toLowerCase();
      // 某些图片 url 可能没有后缀名，默认是 png
      return canvas.toDataURL("image/" + extension, 1);
    },

    // 下载图片
    downloadArt(hash) {
      console.log(hash);
      let url = this.ipfsHash + hash;
      let downloadName = hash;
      const link = document.createElement("a");
      link.setAttribute("download", downloadName);
      const image = new Image();
      // 添加时间戳，防止浏览器缓存图片
      image.src = url + "?timestamp=" + new Date().getTime();
      // 设置 crossOrigin 属性，解决图片跨域报错
      image.setAttribute("crossOrigin", "Anonymous");
      image.onload = () => {
        link.href = this.getImageBase64(image);
        link.click();
      };
    },
  },
};
</script>

<style lang='less' scope>
@media screen and (max-width: 1100px) {
  #art-detail {
    .cover-box {
      padding: 0 !important;
      position: relative !important;
      top: 0 !important;
    }
    .panel {
      margin-top: 20px;
      position: relative !important;
      width: auto !important;
      right: 0 !important;
    }
  }
}
#art-detail {
  .main-box {
    .art-info-box {
      padding: 20px;
      .cover-box {
        transition: all 0.5s ease;
        position: fixed;
        padding: 0 20px;
        top: 60px;
        left: 0;
        right: 520px;
        bottom: 0;
        display: flex;
        justify-content: center;
        align-items: center;

        .cover {
          position: relative;
          img {
            height: 40vw;
            object-fit: contain;
          }
          .download-btn {
            display: none;
            cursor: pointer;
            position: absolute;
            right: 8px;
            bottom: 50px;
            width: 100px;
            padding: 8px 10px;
            text-align: center;
            background: var(--themeColor1);
            color: #fff;
            border-radius: 10px;
          }
        }
        .cover:hover {
          .download-btn {
            display: block;
          }
        }
        .video {
          video {
            width: 100%;
            object-fit: contain;
          }
          .download-btn {
            display: none;
            cursor: pointer;
            position: absolute;
            right: 8px;
            bottom: 50px;
            width: 100px;
            padding: 8px 10px;
            text-align: center;
            background: var(--themeColor1);
            color: #fff;
            border-radius: 10px;
          }
        }
        .video:hover {
          .download-btn {
            display: block;
          }
        }
      }
      .panel {
        transition: all 0.5s ease;
        box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.05);
        -webkit-box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.05);
        -moz-box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.05);
        position: absolute;
        right: 20px;
        width: 500px;
        border-radius: 20px;
        z-index: 1;
        background: #fff;
        .info {
          padding: 35px;
          .art-name {
            font-size: 35px;
            font-weight: bold;
          }
          .count-info {
            display: flex;
            justify-content: space-between;
            span {
              margin-right: 10px;
            }
            .like-btn {
              border: 1px solid var(--themeColor1);
              height: 30px;
              padding: 5px 0px 5px 15px;
              border-radius: 99px;
              display: flex;
              justify-content: center;
              align-items: center;
              color: var(--themeColor1);
              transition: all 0.2s;
              cursor: pointer;
              i {
                font-size: 20px;
              }
              .like-count {
                margin-left: 5px;
                border-radius: 50%;
                background: #fff;
                height: 20px;
                width: 20px;
                padding: 2px;
                text-align: center;
                color: var(--themeColor1);
              }
            }
            .like-btn:hover {
              background: var(--themeColor1);
              color: #fff;
            }
            .liked {
              background: var(--themeColor1);
              color: #fff;
            }
          }
          .create-time {
            margin-top: 10px;
          }
          .tip {
            margin-top: 20px;
            font-size: 14px;
            color: #333;
          }
          .creatorInfo-owner-box {
            display: flex;
            .user-box:hover {
              background: var(--themeColor4);
              color: #fff;
            }
            .user-box {
              transition: 0.2s;
              cursor: pointer;
              margin-right: 30px;
              margin-top: 10px;
              display: flex;
              align-items: center;
              box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.05);
              padding: 8px;
              padding-right: 30px;
              border-radius: 30px;
              .nickname {
                margin-left: 10px;
                font-size: 14px;
              }
              .avatar {
                width: 30px;
                height: 30px;
                border-radius: 50%;
                overflow: hidden;
                img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }
              }
            }
          }
          .collection-box:hover {
            box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);
          }
          .collection-box {
            transition: 0.2s;
            cursor: pointer;
            margin-top: 10px;
            display: inline-block;
            padding: 10px;
            padding-right: 30px;
            border-radius: 10px;
            box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.05);
            .collection {
              display: flex;
              align-items: center;
              .col-cover {
                width: 30px;
                height: 30px;
                img {
                  width: 100%;
                  height: 100%;
                  border-radius: 5px;
                  object-fit: cover;
                }
              }
              .col-name {
                margin-left: 10px;
                font-size: 14px;
              }
            }
          }
          .desc {
            margin-top: 10px;
            text-indent: 1.5em;
            font-size: 14px;
            line-height: 1.5em;
            color: #333;
          }
          .bid-time-box {
            margin-top: 20px;
            display: flex;
            width: 100%;
            height: 60px;
            background: var(--themeColor1);
            border-radius: 10px;
            color: #fff;
            align-items: center;
            padding: 20px;
            .bid-tip {
            }
            .bid-time {
              margin-left: 20px;
            }
          }
          .gray {
            background: #eee;
          }
          .warring {
            background: rgb(255, 141, 42);
          }
          .history-header {
            margin-top: 30px;
            display: flex;
            .history-tip {
              margin-right: 15px;
              font-size: 14px;
              padding-bottom: 4px;
              cursor: pointer;
            }
            .active {
              border-bottom: 3px solid var(--themeColor1);
            }
          }
        }
        .btn-box {
          background: #fff;
          display: flex;
          align-items: center;
          border-radius: 0 0 20px 20px;
          width: 100%;
          padding: 30px;
          padding-bottom: 30px;
          border-top: 1px solid #eee;
          .price {
            font-size: 18px;
            font-weight: bold;
            color: #666;
            i {
              color: var(--themeColor4);
            }
          }
          .buy-btn {
            cursor: pointer;
            margin-left: 20px;
            background: var(--themeColor1);
            padding: 10px 20px;
            border-radius: 20px;
            color: #fff;
          }
          .buy-btn-gray {
            cursor: not-allowed;
            margin-left: 20px;
            background: #eee;
            padding: 10px 20px;
            border-radius: 20px;
            color: #fff;
          }
        }
      }
    }
  }
  .detail-mask {
    z-index: -1;
    position: fixed;
    // filter: blur(30px) ;
    filter: blur(20px);
    -webkit-mask-image: linear-gradient(rgb(255, 255, 255), transparent);
    -webkit-mask-position-x: initial;
    -webkit-mask-position-y: initial;
    -webkit-mask-size: initial;
    -webkit-mask-repeat-x: initial;
    -webkit-mask-repeat-y: initial;
    -webkit-mask-origin: initial;
    -webkit-mask-clip: initial;
    top: -30px;
    left: -30px;
    right: -30px;
    bottom: -30px;
  }
}
</style>